﻿/*
* Copyright 2009-2010 AKABANA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Windows;

using Akabana.Amf.Messaging.Component;
using Akabana.Amf.Messaging.Service;
using Akabana.Amf.Util;

namespace Akabana.Amf.Messaging
{
    public static class ApplicationExt
    {
        public const string GATEWAY_URL = "gatewayUrl";

        private const string SERVICE = "Service";

        public static void InitServices(this Application app, IDictionary<String, String> InitParams)
        {
            
            ApplicationGlobals.InitParams = InitParams;

            InitAssemblyLoad(app);

            InitGatewayUrl();

            if (app.RootVisual != null)
            {
                setupServices(app.RootVisual);
            }
        }

        private static void setupServices(UIElement Root)
        {
            var pageType = Root.GetType();

            foreach (var field in pageType.GetFields())
            {
                if (field.Name.IndexOf(SERVICE) > 0)
                {
                    var attributes = field.FieldType.GetCustomAttributes(true);

                    foreach (var attribute in attributes)
                    {
                        if (attribute is MessagingServiceAttribute)
                        {
                            field.SetValue(Root, ServiceFactory.NewInstance(field.FieldType));
                            break;
                        }
                    }
                }
            }
        }

        private static void InitGatewayUrl()
        {
            string GatewayUrl;
            if (ApplicationGlobals.InitParams.TryGetValue(GATEWAY_URL, out GatewayUrl))
            {
                ServiceFactory.Initialize(GatewayUrl);
            }
            else
            {
                ServiceFactory.Initialize(null);
            }
        }

        private static void InitAssemblyLoad(Application app)
        {
            AssemblyLoader.Initialize(app.GetType().Assembly);
        }
    }
}
